package com.hui.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hui.admin.common.UserContext;
import com.hui.admin.common.enums.ErrorCodeEnum;
import com.hui.admin.common.exception.UserException;
import com.hui.admin.dto.request.ArticlePageRequestDTO;
import com.hui.admin.dto.request.ArticleSaveRequestDTO;
import com.hui.admin.dto.response.ArticleCategoryResponseDTO;
import com.hui.admin.dto.response.ArticleListDTO;
import com.hui.admin.dto.response.ArticlePageResponseDTO;
import com.hui.admin.entity.ArticleDO;
import com.hui.admin.entity.CategoryDO;
import com.hui.admin.entity.UserDO;
import com.hui.admin.mapper.ArticleMapper;
import com.hui.admin.service.ArticleService;
import com.hui.admin.service.CategoryService;
import com.hui.admin.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, ArticleDO> implements ArticleService {

    @Resource
    private CategoryService categoryService;

    @Resource
    private UserService userService;

    @Override
    public ArticlePageResponseDTO getArticleList(ArticlePageRequestDTO requestDTO) {
        // 获取当前用户 ID
        Long currentUserId = UserContext.getCurrentUserId();

        // 分页对象
        Page<ArticleDO> page = new Page<>(requestDTO.getPageNum(), requestDTO.getPageSize());

        // 构造查询条件
        LambdaQueryWrapper<ArticleDO> queryWrapper = new LambdaQueryWrapper<>();

        if (!StrUtil.isEmpty(requestDTO.getTitle())) {
            queryWrapper.like(ArticleDO::getTitle, requestDTO.getTitle());
        }

        // 按发布时间降序排列
        queryWrapper.orderByDesc(ArticleDO::getPublishTime);

        // 只查当前用户的文章
        queryWrapper.eq(ArticleDO::getUserId, currentUserId);

        // 文章列表
        Page<ArticleDO> resultPage = baseMapper.selectPage(page, queryWrapper);

        // 转换 DO 到 DTO
        List<ArticleListDTO> dtoList = resultPage.getRecords().stream().map(articleDO -> {
            ArticleListDTO dto = new ArticleListDTO();
            dto.setId(articleDO.getId());
            dto.setTitle(articleDO.getTitle());
            dto.setCover(articleDO.getCover());
            dto.setContent(articleDO.getContent());
            dto.setPublishTime(articleDO.getPublishTime());
            dto.setCategoryId(articleDO.getCategoryId());
            dto.setUserId(articleDO.getUserId());

            dto.setCategoryName(
                    Optional.ofNullable(categoryService.getById(articleDO.getCategoryId()))
                            .map(CategoryDO::getCategoryName)
                            .orElse(null)
            );

            dto.setUserName(
                    Optional.ofNullable(userService.getById(articleDO.getUserId()))
                            .map(UserDO::getName)
                            .orElse(null)
            );
            return dto;
        }).toList();

        // 构造返回对象
        ArticlePageResponseDTO result = new ArticlePageResponseDTO();
        result.setList(dtoList);
        result.setTotal(resultPage.getTotal());

        return result;
    }

    @Override
    public void createArticle(ArticleSaveRequestDTO requestDTO) {
        Long currentUserId = UserContext.getCurrentUserId();
        if (currentUserId == null) {
            throw new UserException(ErrorCodeEnum.USER_NOT_LOGIN);
        }
        requestDTO.setUserId(currentUserId);
        ArticleDO result = BeanUtil.copyProperties(requestDTO, ArticleDO.class);

        if (result == null) {
            throw new UserException(ErrorCodeEnum.ARTICLE_ADD_FAILED);
        }

        boolean flag = save(result);

        if (!flag) {
            throw new UserException(ErrorCodeEnum.ARTICLE_ADD_FAILED);
        }
    }

    @Override
    public void updateArticle(ArticleSaveRequestDTO requestDTO) {
        LambdaQueryWrapper<ArticleDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ArticleDO::getId, requestDTO.getId());
        ArticleDO articleDO = getOne(queryWrapper);
        if (articleDO == null) {
            throw new UserException(ErrorCodeEnum.ARTICLE_NOT_EXISTS);
        }
        ArticleDO result = BeanUtil.copyProperties(requestDTO, ArticleDO.class);
        boolean flag = updateById(result);
        if (!flag) {
            throw new UserException(ErrorCodeEnum.ARTICLE_NOT_EXISTS);
        }
    }

    @Override
    public void deleteArticle(Long id) {
        if (id == null) {
            throw new UserException(ErrorCodeEnum.ARTICLE_NOT_EXISTS);
        }

        boolean flag = removeById(id);

        if (!flag) {
            throw new UserException(ErrorCodeEnum.ARTICLE_NOT_EXISTS);
        }
    }

    @Override
    public void deleteArticles(Long[] ids) {
        if (ids == null || ids.length == 0) {
            throw new UserException(ErrorCodeEnum.ARTICLE_NOT_EXISTS);
        }

        boolean flag = removeByIds(Arrays.asList(ids));

        if (!flag) {
            throw new UserException(ErrorCodeEnum.ARTICLE_NOT_EXISTS);
        }
    }

    @Override
    public List<ArticleCategoryResponseDTO> getCategoryList() {
        return categoryService.list().stream()
                .map(category -> {
                    ArticleCategoryResponseDTO dto = new ArticleCategoryResponseDTO();
                    dto.setId(category.getId());
                    dto.setCategoryName(category.getCategoryName());
                    return dto;
                })
                .toList();
    }
}
